package com.tepth.maintenancesystem.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nshmura.recyclertablayout.RecyclerTabLayout;
import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.SysApplication;
import com.tepth.maintenancesystem.api.HttpClient;
import com.tepth.maintenancesystem.api.MaintainHttp;
import com.tepth.maintenancesystem.api.OutLogin;
import com.tepth.maintenancesystem.bean.Contents;
import com.tepth.maintenancesystem.bean.MaintainDriverAndRemark;
import com.tepth.maintenancesystem.bean.MaintainListWork;
import com.tepth.maintenancesystem.bean.VehicleMaintain;
import com.tepth.maintenancesystem.presenter.HistoryItemClickListener;
import com.tepth.maintenancesystem.presenter.InitViewPager;
import com.tepth.maintenancesystem.presenter.MaintainDetailsAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsLeftAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsRightAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsRightOnClick;
import com.tepth.maintenancesystem.presenter.MaintainHistoryAdapter;
import com.tepth.maintenancesystem.untils.AESUtils;
import com.tepth.maintenancesystem.untils.DimensionConvert;
import com.tepth.maintenancesystem.untils.ToastUtils;
import com.tepth.maintenancesystem.untils.Untils;
import com.tepth.maintenancesystem.view.fragment.GuojianBottomFragment;
import com.tepth.maintenancesystem.view.zxingcapture.CaptureActivity;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MaintainDetailsActivitiy extends AppCompatActivity implements InitViewPager, MaintainDetailsRightOnClick, HistoryItemClickListener, OutLogin {

    private MaintainDetailsLeftAdapter leftAdapter;
    private MaintainDetailsRightAdapter rightAdapter;

    private MaintainHistoryAdapter historyAdapter;//历史保养记录列表
    private LinearLayout nodata_notification_history;

    private ListView leftListView;
    private ListView rightListView;
    private RecyclerView historyListView;

    private List<VehicleMaintain> listHistory = new ArrayList<>();
    private Context context;
    private ArrayList<MaintainListWork> listWorks = new ArrayList<>();
    private List<Contents> doingWorks = new ArrayList<>();//做了的集合
    private List<Contents> undoWorks = new ArrayList<>();//取消的集合

    private ArrayList<MaintainListWork> doingGuojian = new ArrayList<>();//过检的集合
    private ArrayList<MaintainListWork> undoGuojian = new ArrayList<>();//取消的过检集合
    private VehicleMaintain obj;
    private LoadingDialog loadingDialog;

    private RecyclerTabLayout mRecyclerTabLayout;

    private RelativeLayout rl_work_barcode, rl_work_back;
    private LinearLayout linear_guojian_barcode, linear_junjian_barcode;
    private TextView tv_work_title, tv_work_bottom_name, tv_maintain_remark;
    private String name, number;//要提交的作业人的姓名和员工编号
    private GuojianBottomFragment bottomFragment;
    private MaintainDriverAndRemark remark;
    private String dateString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintain_details);
        SysApplication.getInstance().addActivity(this);
        context = this;
        Bundle bundle = this.getIntent().getBundleExtra("MaintainBundle");
        obj = (VehicleMaintain) bundle.getSerializable("Maintain");
        dateString = bundle.getString("dateString");
        MaintainDetailsAdapter adapter = new MaintainDetailsAdapter(this);
        ViewPager viewPager = (ViewPager) findViewById(R.id.maintain_pager);
        viewPager.setAdapter(adapter);
        mRecyclerTabLayout = (RecyclerTabLayout) findViewById(R.id.maintain_tablayout);
        mRecyclerTabLayout.setTabMinWidth(DimensionConvert.getWidth2(this));//设置tab宽度
        mRecyclerTabLayout.setUpWithViewPager(viewPager);

        tv_work_title = (TextView) findViewById(R.id.tv_work_title);
        tv_work_title.setText(obj.getVehicleNumber() + "  保养作业");
        rl_work_back = (RelativeLayout) findViewById(R.id.rl_work_back);
        rl_work_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(MaintainHttp.RESULT_REFRESHLIST);
                finish();
            }
        });
    }

    private void initView(View view) {
        leftListView = (ListView) view.findViewById(R.id.left_listview);
        rightListView = (ListView) view.findViewById(R.id.right_listview);
        rl_work_barcode = (RelativeLayout) view.findViewById(R.id.rl_work_barcode);
        linear_guojian_barcode = (LinearLayout) view.findViewById(R.id.linear_guojian_barcode);
        linear_junjian_barcode = (LinearLayout) view.findViewById(R.id.linear_junjian_barcode);
        tv_work_bottom_name = (TextView) view.findViewById(R.id.tv_work_bottom_name);
//        tv_guojian_bottom_name = (TextView) view.findViewById(R.id.tv_guojian_bottom_name);
        tv_maintain_remark = (TextView) view.findViewById(R.id.tv_maintain_remark);
        if (doingWorks.size() > 0) {
            rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.green_scan_to_barcode_n));
        } else {
            rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.grey_scan_to_barcode));
        }
        rl_work_barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (doingWorks.size() == 0 && undoWorks.size() == 0)
                    return;
                Intent intent = new Intent();
                intent.setClass(context, NFCDialogActivity.class);
                startActivityForResult(intent, 1002);
            }
        });
        linear_guojian_barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm = getSupportFragmentManager();
                bottomFragment = GuojianBottomFragment.newInstance(listWorks);
                bottomFragment.show(fm, "guojian_bottom");
            }
        });
        linear_junjian_barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = MaintainDetailsActivitiy.this.getIntent().getBundleExtra("MaintainBundle");
                Intent intent = new Intent();
                intent.setClass(context, MaintainCompletedActivity.class);
                intent.putExtra("MaintainBundle", bundle);
                intent.putExtra("dateString", dateString);
                startActivity(intent);
            }
        });
    }

    private void initHistoryView(View view) {
        historyListView = (RecyclerView) view.findViewById(R.id.maintain_list_history);
        nodata_notification_history = (LinearLayout) view.findViewById(R.id.nodata_notification_history);
    }

    /**
     * @param obj
     * @param type
     */
    public void guojian_list_Listener(MaintainListWork obj, int type) {
        switch (type) {
            case 0:
                doingGuojian.add(obj);
                break;
            case 1:
                doingGuojian.remove(obj);
                break;
            case 2:
                undoGuojian.add(obj);
                break;
            case 3:
                undoGuojian.remove(obj);
                break;
        }
    }

    public void guojian_bottomListen() {
        if (doingGuojian.size() == 0 && undoGuojian.size() == 0)
            return;
        Intent intent = new Intent();
        intent.setClass(context, NFCDialogActivity.class);
        startActivityForResult(intent, 1003);
    }

    public boolean isHaveGuojianListSize() {
        if (doingGuojian.size() == 0 && undoGuojian.size() == 0) {
            return false;
        } else {
            return true;
        }
    }

    private void getDriverAndRemark() {
        if (remark != null) {
            getListWorkContentsNormal();
            return;
        }
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setInterceptBack(false)
                .setLoadingText("正在加载...");
        loadingDialog.show();
        new Thread() {
            @Override
            public void run() {
                remark = MaintainHttp.getDriverAndRemark(context, obj.getId() + "");
                myHandler.sendEmptyMessage(3);
                super.run();
            }
        }.start();
    }

    /**
     * 请求保养项目列表
     */
    private void getListWorkContentsNormal() {
        if (listWorks.size() > 0) {
            initLeftListView();
            return;
        }
        new Thread() {
            @Override
            public void run() {
                listWorks = MaintainHttp.getListWork(context, obj.getId(), MaintainDetailsActivitiy.this);
                myHandler.sendEmptyMessage(0);
                super.run();
            }
        }.start();
    }

    private void getHistoryMaintain() {
        if (listHistory.size() > 0) {
            nodata_notification_history.setVisibility(View.GONE);
            historyListView.setVisibility(View.VISIBLE);
            return;
        }
        new Thread() {
            @Override
            public void run() {
                listHistory = MaintainHttp.getListHistory(context, obj.getVehicleNumber());
                myHandler.sendEmptyMessage(4);
                super.run();
            }
        }.start();
    }

    private void initHistoryAdapter() {
        historyListView.setVisibility(View.VISIBLE);
        historyAdapter = new MaintainHistoryAdapter(context, listHistory);
        historyAdapter.setOnItemClickListener(this);
        //使用线性布局
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        historyListView.setLayoutManager(layoutManager);
        historyListView.setHasFixedSize(true);
        historyListView.setAdapter(historyAdapter);
    }

    private void initLeftListView() {
        leftAdapter = new MaintainDetailsLeftAdapter(this, listWorks);
        leftAdapter.setSelectPosition(0);
        leftListView.setAdapter(leftAdapter);
        initRightListView(listWorks.get(0).getListContents());
        initBottomName(leftAdapter.getCurrentPositionItem());
        leftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updataRightListView(position);
                initBottomName(leftAdapter.getCurrentPositionItem());
            }
        });
    }

    private void initRightListView(List<Contents> listContents) {
        rightAdapter = new MaintainDetailsRightAdapter(this, listContents, this);
        rightListView.setAdapter(rightAdapter);
    }

    private void updataRightListView(int position) {
        leftAdapter.setSelectPosition(position);
        leftAdapter.notifyDataSetChanged();
        //更新第二ListView
        rightAdapter.setDatas(listWorks.get(position).getListContents());
        rightAdapter.notifyDataSetChanged();
    }

    private void initBottomName(MaintainListWork left_select) {
        String totalName = "";
        for (int i = 0; i < left_select.getListContents().size(); i++) {
            if (left_select.getListContents().get(i).getWorkPersonName().equals("null") || left_select.getListContents().get(i).getWorkPersonName().equals(""))
                continue;
            if (!totalName.contains(left_select.getListContents().get(i).getWorkPersonName())) {
                totalName += left_select.getListContents().get(i).getWorkPersonName() + ",";
            }
        }
        if (!totalName.equals(""))
            totalName = totalName.substring(0, totalName.length() - 1);
        tv_work_bottom_name.setText("作业人：" + totalName);
//        String name = "";
//        if (left_select.getConfirmPersonName().equals("null") || left_select.getConfirmPersonName().equals("")) {
//            name = "";
//        } else {
//            name = left_select.getConfirmPersonName();
//        }
//        tv_guojian_bottom_name.setText("过检员：" + name);
    }

    @Override
    public void initViewPager(View view, int position) {
        switch (position) {
            case 0:
                initView(view);
                getDriverAndRemark();
                break;
            case 1:
                initHistoryView(view);
                break;
            case 2:
                break;
        }
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://初始化作业列表
//                    loadingDialog.close();
                    if (listWorks != null) {
                        initLeftListView();
                    } else {
                        ToastUtils.showToast(context, "网络错误");
                    }
                    getHistoryMaintain();
                    break;
                case 1://保存作业结果
                    loadingDialog.close();
                    String update_code = msg.getData().getString("update_code");
                    if (update_code.equals(HttpClient.SUCCESS)) {//保存成功
                        for (int j = 0; j < listWorks.size(); j++) {
                            MaintainListWork work = listWorks.get(j);
                            work.setTemp_select_number(0);
                            for (int i = 0; i < doingWorks.size(); i++) {//更改listWorks集合，并刷新右侧Adapter
                                Contents doingContents = doingWorks.get(i);
                                if (doingContents.getContentTypeCode().equals(work.getContentTypeCode())) {
                                    for (int k = 0; k < work.getListContents().size(); k++) {
                                        Contents work_content = work.getListContents().get(k);
                                        if (work_content.getId() == doingContents.getId()) {
                                            work_content.setValue(doingContents.getValue());
                                            work_content.setWorkPersonCode(number);
                                            work_content.setWorkPersonName(name);
                                        }
                                    }
                                }
                            }
                            for (int m = 0; m < undoWorks.size(); m++) {
                                Contents undoContents = undoWorks.get(m);
                                if (undoContents.getContentTypeCode().equals(work.getContentTypeCode())) {
                                    for (int k = 0; k < work.getListContents().size(); k++) {
                                        Contents undoWork_content = work.getListContents().get(k);
                                        if (undoWork_content.getId() == undoContents.getId()) {
                                            undoWork_content.setValue("");
                                            undoWork_content.setWorkPersonCode("null");
                                            undoWork_content.setWorkPersonName("null");
                                            undoWork_content.setRemark("");
                                        }
                                    }
                                }
                            }
                        }
                        rightAdapter.notifyDataSetChanged();//刷新右侧Adapter
                        leftAdapter.notifyDataSetChanged();//刷新左边Adapter
                        rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.grey_scan_to_barcode));//按钮变灰色
                        ToastUtils.showToast(context, "保存成功");
                        doingWorks.clear();
                        undoWorks.clear();
                    } else if (update_code.equals(HttpClient.ERROR_USER)) {//用户过期
                        ToastUtils.showToast(context, "请重新登录");
                    } else {
                        ToastUtils.showToast(context, "保存失败");
                    }
                    break;
                case 2://保存成功过检
                    loadingDialog.close();
                    bottomFragment.dismiss();
                    String update_code2 = msg.getData().getString("update_code");
                    if (update_code2.equals(HttpClient.SUCCESS)) {//保存成功
                        for (int j = 0; j < listWorks.size(); j++) {
                            MaintainListWork work = listWorks.get(j);
                            for (int i = 0; i < doingGuojian.size(); i++) {//更改listWorks集合
                                if (doingGuojian.get(i).getContentTypeCode().equals(work.getContentTypeCode())) {
                                    work.setConfirmPersonCode(number);
                                    work.setConfirmPersonName(name);
                                }
                            }
                            for (int m = 0; m < undoGuojian.size(); m++) {
                                if (undoGuojian.get(m).getContentTypeCode().equals(work.getContentTypeCode())) {
                                    work.setConfirmPersonCode("null");
                                    work.setConfirmPersonName("null");
                                }
                            }
                        }
                        leftAdapter.notifyDataSetChanged();//刷新左边Adapter
                        ToastUtils.showToast(context, "保存成功");
                        doingGuojian.clear();
                        undoGuojian.clear();
                    } else if (update_code2.equals(HttpClient.ERROR_USER)) {//用户过期
                        ToastUtils.showToast(context, "请重新登录");
                    } else {
                        ToastUtils.showToast(context, "保存失败");
                    }
                    break;
                case 3://展示保养报修信息
//                        if(remark.getRemark().equals("")){}
                    tv_maintain_remark.setText("报修信息:" + remark.getRemark());
                    getListWorkContentsNormal();
                    break;
                case 4://展示这辆车的历史保养记录
                    loadingDialog.close();
                    if (listHistory != null) {
                        initHistoryAdapter();
                    } else {
                        nodata_notification_history.setVisibility(View.VISIBLE);
                        historyListView.setVisibility(View.GONE);
                    }
                    break;
                case 5:
                    ToastUtils.showToast(context, "登录超时");
                    Intent intent2 = new Intent();
                    intent2.setClass(context, LoginActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent2.putExtra("manual", "manual");
                    startActivity(intent2);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void checkboxOnClick(Contents object, int type) {
        int temp = leftAdapter.getCurrentPositionItem().getTemp_select_number();
        switch (type) {
            case 0:
                doingWorks.add(object);
                leftAdapter.getCurrentPositionItem().setTemp_select_number(temp + 1);
                break;
            case 1:
                doingWorks.remove(object);
                if (temp > 0) {
                    leftAdapter.getCurrentPositionItem().setTemp_select_number(temp - 1);
                }
                break;
            case 2:
                undoWorks.remove(object);
                if (temp > 0)
                    leftAdapter.getCurrentPositionItem().setTemp_select_number(temp - 1);
                break;
            case 3:
                undoWorks.add(object);
                leftAdapter.getCurrentPositionItem().setTemp_select_number(temp + 1);
                break;
        }
        leftAdapter.notifyDataSetChanged();
        if (doingWorks.size() == 0 && undoWorks.size() == 0) {
            rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.grey_scan_to_barcode));
        } else {
            rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.green_scan_to_barcode_n));
        }

    }

    @Override
    public void textOnClick(Contents object) {
//        String workName="";
//        for (int i=0;i<listWorks.size();i++){
//            if(object.getContentTypeCode().equals(listWorks.get(i).getContentTypeCode())){
//                workName=listWorks.get(i).getContentTypeName();
//            }
//        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putParcelable("contents", object);
        bundle.putString("workName", leftAdapter.getCurrentPositionItem().getContentTypeName());
        bundle.putString("vehicleName", obj.getVehicleNumber());
        intent.putExtra("bundle", bundle);
        if (object.getWorkPersonName().equals("null") || object.getWorkPersonName().equals("")) {
            intent.setClass(context, MaintainWorkDetailsActivity.class);
            startActivityForResult(intent, 1004);
        } else {
            intent.setClass(context, MaintainWorkCompletedDetailsActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == MaintainHttp.BARCODE_RESULTCODE) {
                CharSequence displayContents = data.getCharSequenceExtra("BarCodeContents");
                update(displayContents.toString(), requestCode);
            } else if (resultCode == MaintainHttp.NFC_RESULTCODE) {
                byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
                try {
                    update(new String(displayContents, "utf-8"), requestCode);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 1004 && resultCode == MaintainHttp.RESULT_REFERSHOBJECT) {
                Contents obj = data.getBundleExtra("maintainBundle").getParcelable("MaintainObj");
                MaintainListWork leftObj = leftAdapter.getCurrentPositionItem();
                for (int i = 0; i < leftObj.getListContents().size(); i++) {
                    Contents rightObjs = leftObj.getListContents().get(i);
                    if (obj.getId() == rightObjs.getId()) {
                        rightObjs.setValue(obj.getValue());
                        rightObjs.setRemark(obj.getRemark());

                    }
                }
                initRightListView(leftObj.getListContents());
                boolean isContains = false;
                for (Contents content : doingWorks) {
                    if (content.getId() == obj.getId()) {
                        isContains = true;
                        content.setValue(obj.getValue());
                        content.setRemark(obj.getRemark());
                        break;
                    }
                }
                if (!isContains) {
                    doingWorks.add(obj);
                    rl_work_barcode.setBackgroundColor(Untils.getColor(context, R.color.green_scan_to_barcode_n));
                    int temp = leftAdapter.getCurrentPositionItem().getTemp_select_number();
                    leftAdapter.getCurrentPositionItem().setTemp_select_number(temp + 1);
                    leftAdapter.notifyDataSetChanged();
                }
            } else if (resultCode == MaintainHttp.RETURN_BARCODE) {
                Intent intent = new Intent();
                intent.setClass(context, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            }
        } catch (Exception el) {
            el.printStackTrace();
            ToastUtils.showToast(context, "保存失败");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void update(String contents, final int requestCode) {
        String result = "";
        try {
            result = AESUtils.code_desEncrypt(contents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == "") {
            ToastUtils.showToast(context, "保存失败");
            return;
        }
        String[] results = result.split("_");
        if (result.length() < 2) {
            ToastUtils.showToast(context, "保存失败");
            return;
        }
        number = results[0];
        name = results[1];
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setInterceptBack(false)
                .setLoadingText("正在保存...");
        loadingDialog.show();

        new Thread() {
            @Override
            public void run() {
                String result_data = "[";
                try {
                    int type = 0;
                    Message msg = new Message();
                    if (requestCode == 1002) {
                        type = 0;
                        msg.what = 1;
                        for (int i = 0; i < doingWorks.size(); i++) {
                            Contents doing = doingWorks.get(i);
                            JSONObject object = new JSONObject();
                            object.put("Id", doing.getId());
                            object.put("Value", doing.getValue());
                            object.put("WorkPersonCode", number);
                            object.put("WorkPersonName", name);
                            object.put("Remark", doing.getRemark());
                            result_data += object.toString() + ",";
                        }
                        for (int i = 0; i < undoWorks.size(); i++) {
                            Contents undo = undoWorks.get(i);
                            JSONObject object = new JSONObject();
                            object.put("Id", undo.getId());
                            object.put("Value", undo.getValue());
                            object.put("WorkPersonCode", "");
                            object.put("WorkPersonName", "");
                            object.put("Remark", "");
                            result_data += object.toString() + ",";
                        }
                        result_data = result_data.substring(0, result_data.length() - 1);
                        result_data += "]";
                    } else if (requestCode == 1003) {
                        type = 1;
                        msg.what = 2;
                        for (int i = 0; i < doingGuojian.size(); i++) {
                            MaintainListWork doing = doingGuojian.get(i);
                            JSONObject object = new JSONObject();
                            object.put("ContentTypeCode", doing.getContentTypeCode());
                            object.put("ConfirmType", 1);
                            object.put("ConfirmPersonCode", number);
                            object.put("ConfirmPersonName", name);
                            object.put("remark", doing.getCompletedRemark());
                            result_data += object.toString() + ",";
                        }
                        for (int i = 0; i < undoGuojian.size(); i++) {
                            MaintainListWork undo = undoGuojian.get(i);
                            JSONObject object = new JSONObject();
                            object.put("ContentTypeCode", undo.getContentTypeCode());
                            object.put("ConfirmType", 1);
                            object.put("ConfirmPersonCode", "");
                            object.put("ConfirmPersonName", "");
                            result_data += object.toString() + ",";
                        }
                        result_data = result_data.substring(0, result_data.length() - 1);
                        result_data += "]";
                    }
                    String result_code = MaintainHttp.updateWorkContentsAndConfirm(context, obj.getId(), type, result_data);
                    Bundle bundle = new Bundle();
                    bundle.putString("update_code", result_code);
                    msg.setData(bundle);
                    myHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(MaintainHttp.RESULT_REFRESHLIST);
            this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(View view, int postion) {
        VehicleMaintain historyObj = listHistory.get(postion);
        Intent intent = new Intent();
        intent.setClass(context, MaintainHistoryDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("Maintain", historyObj);
        intent.putExtra("MaintainBundle", bundle);
        startActivity(intent);
    }

    @Override
    public void outLogin() {
        myHandler.sendEmptyMessage(5);
    }
}
